<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace backend\models;

use yii\base\Model;
use common\models\User;
use yii\web\Cookie;
use Yii;
/**
 * Description of LoginForm
 *
 * @author zhige
 */
class LoginForm extends Model{
    //put your code here
    public $username;
    public $password;
    public $verifyCode;
    public $remember;
    
    private $user;
    const BACKEND_ID = 'backend_id';
    const BACKEND_USERNAME = 'backend_username';
    const BACKEND_COOKIE = 'backend_remember';
    
    public function rules(){
        return [
          ['username','validateAccount','skipOnEmpty'=>false],
            ['verifyCode','captcha',
                'captchaAction'=>'login/captcha',
                'message'=>'验证码错误'],
            [['password','remember'],'safe'],
        ];
    }
    
    public function validateAccount($attribute,$params){
        if(!preg_match('/^\w{2,30}$/', $this->$attribute)){
            $this->addError($attribute,'账号或密码不符合规定');
        }
        else if(strlen($this->password) < 6){
            $this->addError($attribute,'密码太短了。');
        }else{
            $user = User::find()->where([
                'username'=> $this->$attribute,'status'=>1
            ])->asArray()->one();
            if(!$user){
                $this->addError($attribute,'用户不存在');
            }else if(md5($this->password) != $user['password']){
                $this->addError($attribute,'登录密码错误');
            }else{
                $this->user = $user;
            }
        }
    }
    
    public function login(){
        if(!$this->user){
            return false;
        }
//        $this->createSession();
        
        //如果记住登录状态是1
        if($this->remember == 1){
            $this->createCookie();
        }
        
//        $this->updateUserStatus();
        return true;
    }
    
    public function createSession(){
        //第一步生成session
        $session = Yii::$app->session;
        $session->set(self::BACKEND_ID,$this->user['id']);
        $session->set(self::BACKEND_USERNAME,$this->user['username']);
    }
    
    public function createCookie() {
        $cookie = new Cookie();
        $cookie->name = self::BACKEND_COOKIE;
        $cookie->value = [
            'id' => $this->user['id'],
            'username' => $this->user['username']
        ];

        //cookie保存7天
        $cookie->expire = time() + 60 * 60 * 24 * 7;
        $cookie->httpOnly = true;

        Yii::$app->response->cookies->add($cookie);
    }
    
    public function updateUserStatus(){
        
        $user = User::findOne($this->user['id']);
//        $user->login_ip = Yii::$app->request->getUserIP();
        $user->login_date = time();
        return $user->save();
    }

}
